package database

import (
	"fmt"
	"n-server/config"
	"n-server/internal/model"
	"n-server/pkg/logger"
	"time"

	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	gormLogger "gorm.io/gorm/logger"
)

var db *gorm.DB

// Init 初始化 MySQL 数据库连接
func Init(c *config.DatabaseConfig) (*gorm.DB, error) {
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		c.User, c.Password, c.Host, c.Port, c.DBName,
	)

	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: gormLogger.Default.LogMode(gormLogger.Info), // GORM 日志模式
	})
	if err != nil {
		logger.L().Fatal("⚠️ Failed to connect to database", zap.Error(err))
		return nil, err
	}

	sqlDB, err := db.DB()
	if err != nil {
		logger.L().Fatal("⚠️ Failed to get generic database object", zap.Error(err))
		return nil, err
	}

	// 设置连接池
	sqlDB.SetMaxIdleConns(c.MaxIdleConns)
	sqlDB.SetMaxOpenConns(c.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(c.ConnMaxLifetime * time.Minute)

	// 自动迁移数据库
	if err = db.AutoMigrate(&model.User{}); err != nil {
		logger.L().Fatal("⚠️ Failed to auto migrate database", zap.Error(err))
		return nil, err
	}
	logger.L().Info("🚚 Database auto migrate completed")

	logger.L().Info("Database connection established successfully")
	return db, nil
}

// Close 关闭 MySQL 连接
func Close(db *gorm.DB) {
	sqlDB, err := db.DB()
	if err != nil {
		logger.L().Fatal("⚠️ Failed to get database instance", zap.Error(err))
		return
	}

	if err:= sqlDB.Close(); err != nil {
		logger.L().Fatal("⚠️ Failed to close database", zap.Error(err))
	}
}


